<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>库位设置</title>
  <meta name="renderer" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <link rel="stylesheet" href="../lib/layui-v2.6.3/css/layui.css" media="all">
  <link rel="stylesheet" href="../css/public.css" media="all">
  <style>
    .location-card-list {
      display: flex;
      flex-wrap: wrap;
      gap: 20px;
      margin-top: 20px;
    }

    .location-card {
      width: 260px;
      background: linear-gradient(135deg, #2196f3ff 0%, #21cbf3ff 100%);
      color: #fff;
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
      padding: 18px 20px 16px 20px;
      position: relative;
      margin-bottom: 10px;
      transition: box-shadow 0.2s;
    }

    .location-card.low {
      background: linear-gradient(135deg, #21cbf3ff 0%, #21cbf3ff 100%);
    }

    .location-card.normal {
      background: linear-gradient(135deg, #2196f3ff 0%, #2196f3ff 100%);
    }

    .location-card.warning {
      background: linear-gradient(135deg, #ff9800ff 0%, #ff9800ff 100%);
    }

    .location-card.danger {
      background: linear-gradient(135deg, #f44336ff 0%, #f44336ff 100%);
    }

    .location-card .card-title {
      font-size: 18px;
      font-weight: bold;
      margin-bottom: 8px;
    }

    .location-card .card-status {
      position: absolute;
      top: 18px;
      right: 20px;
      font-size: 14px;
      font-weight: bold;
    }

    .location-card .card-info {
      margin-bottom: 12px;
      font-size: 15px;
    }

    .location-card .card-actions {
      display: flex;
      gap: 8px;
    }

    /* 控制搜索框的长度 */
    .table-search-fieldset .layui-input-inline,
    .table-search-fieldset .layui-select {
      max-width: 120px;
      width: 120px;
    }

    .table-search-fieldset .layui-btn {
      max-width: none;
      width: auto;
    }

    /* 颜色说明 */
    .color-legend {
      display: flex;
      gap: 10px;
      margin: 10px 0;
    }

    .legend-item {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 80px;
      height: 30px;
      color: #fff;
      font-size: 14px;
      border-radius: 4px;
    }

    .legend-content {
      display: inline-block;
    }

    .legend-item.low {
      background: linear-gradient(135deg, #21cbf3ff 0%, #21cbf3ff 100%);
    }

    .legend-item.normal {
      background: linear-gradient(135deg, #2196f3ff 0%, #2196f3ff 100%);
    }

    .legend-item.warning {
      background: linear-gradient(135deg, #ff9800ff 0%, #ff9800ff 100%);
    }

    .legend-item.danger {
      background: linear-gradient(135deg, #f44336ff 0%, #f44336ff 100%);
    }
  </style>
</head>
<body>
<div class="layuimini-container">
  <div class="layuimini-main">

    <!-- 搜索表单 -->
    <fieldset class="table-search-fieldset">
      <form class="layui-form layui-form-pane" id="searchForm">
        <div class="layui-form-item">
          <div class="layui-inline">
            <label class="layui-form-label">仓库</label>
            <div class="layui-input-inline">
              <select name="warehouseId" id="warehouseSelect">
                <option value="">全部</option>
              </select>
            </div>
          </div>
          <div class="layui-inline">
            <label class="layui-form-label">状态</label>
            <div class="layui-input-inline">
              <select name="status">
                <option value="">全部</option>
                <option value="low">空闲</option>
                <option value="normal">正常</option>
                <option value="warning">预警</option>
                <option value="danger">超标</option>
              </select>
            </div>
          </div>
          <div class="layui-inline">
            <label class="layui-form-label">库位编号</label>
            <div class="layui-input-inline">
              <input type="text" name="locationCode" class="layui-input" placeholder="请输入库位编号">
            </div>
          </div>
          <div class="layui-inline">
            <label class="layui-form-label">库位名称</label>
            <div class="layui-input-inline">
              <input type="text" name="locationName" class="layui-input" placeholder="请输入库位名称">
            </div>
          </div>
          <div class="layui-inline">
            <button type="submit" class="layui-btn layui-btn-normal" lay-submit lay-filter="search-btn"><i class="layui-icon"></i> 查询</button>
            <button type="button" class="layui-btn layui-btn-normal" id="reset-btn"><i class="layui-icon layui-icon-refresh"></i> 重置</button>
            <button type="button" class="layui-btn layui-btn-normal" id="add-btn"><i class="layui-icon layui-icon-add-1"></i> 添加库位</button>
          </div>
        </div>
      </form>
    </fieldset>

    <!-- 颜色说明 -->
    <div class="color-legend">
      <div class="legend-item low"><span class="legend-content">空闲</span></div>
      <div class="legend-item normal"><span class="legend-content">正常</span></div>
      <div class="legend-item warning"><span class="legend-content">预警</span></div>
      <div class="legend-item danger"><span class="legend-content">超标</span></div>
    </div>

    <!-- 卡片区 -->
    <div class="location-card-list" id="locationCardList"></div>

    <!-- 添加弹窗 -->
    <div id="addLocationFormDialog" style="display:none;">
      <form class="layui-form layuimini-form" id="addLocationForm">
        <div class="layui-form-item">
          <label class="layui-form-label required">库位编号</label>
          <div class="layui-input-inline">
            <input type="text" name="storageLocationCode" lay-verify="required" placeholder="请输入库位编号" class="layui-input">
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label required">库位名称</label>
          <div class="layui-input-inline">
            <input type="text" name="storageLocationName" lay-verify="required" placeholder="请输入库位名称" class="layui-input">
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label required">库位类型</label>
          <div class="layui-input-inline">
            <input type="text" name="storageLocationType" lay-verify="required" placeholder="请输入库位类型" class="layui-input">
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label">仓库</label>
          <div class="layui-input-inline">
            <select name="warehouseId" id="addWarehouseSelect">
            </select>
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label required">总容量</label>
          <div class="layui-input-inline">
            <input type="number" name="storageLocationTotalCapacity" lay-verify="required" placeholder="请输入总容量" class="layui-input">
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label">已用容量</label>
          <div class="layui-input-inline">
            <input type="number" name="storageLocationUsedCapacity" value="0" readonly class="layui-input">
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label">状态</label>
          <div class="layui-input-inline">
            <select name="storageLocationStatus">
              <option value="low">空闲</option>
              <option value="normal">正常</option>
              <option value="warning">预警</option>
              <option value="danger">超标</option>
            </select>
          </div>
        </div>
        <div class="layui-form-item">
          <div class="layui-input-block">
            <button class="layui-btn layui-btn-normal" lay-submit lay-filter="saveAddLocationBtn">确认添加</button>
          </div>
        </div>
      </form>
    </div>

    <!-- 编辑弹窗 -->
    <div id="editLocationFormDialog" style="display:none;">
      <form class="layui-form layuimini-form" id="editLocationForm" lay-filter="editLocationForm">
        <div class="layui-form-item">
          <label class="layui-form-label ">库位编号</label>
          <div class="layui-input-inline">
            <input type="text" name="storageLocationCode" placeholder="请输入库位编号" class="layui-input">
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label">库位名称</label>
          <div class="layui-input-inline">
            <input type="text" name="storageLocationName"  placeholder="请输入库位名称" class="layui-input">
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label ">库位类型</label>
          <div class="layui-input-inline">
            <input type="text" name="storageLocationType"  placeholder="请输入库位类型" class="layui-input">
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label">位置描述</label>
          <div class="layui-input-block">
            <input type="text" name="storageLocationRemark" placeholder="请输入库位描述" class="layui-input">
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label">仓库</label>
          <div class="layui-input-inline">
            <select name="warehouseId" id="editWarehouseSelect">
            </select>
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label">总容量</label>
          <div class="layui-input-inline">
            <input type="number" name="storageLocationTotalCapacity"  placeholder="请输入总容量" class="layui-input">
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label">已用容量</label>
          <div class="layui-input-inline">
            <input type="number" name="storageLocationUsedCapacity" placeholder="请输入已用容量" class="layui-input">
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label">状态</label>
          <div class="layui-input-inline">
            <select name="storageLocationStatus">
              <option value="low">空闲</option>
              <option value="normal">正常</option>
              <option value="warning">预警</option>
              <option value="danger">超标</option>
            </select>
          </div>
        </div>
        <div class="layui-form-item">
          <div class="layui-input-block">
            <button class="layui-btn layui-btn-normal" lay-submit lay-filter="saveEditLocationBtn">确认修改</button>
          </div>
        </div>
      </form>
    </div>

  </div>
</div>

<script src="../lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
<script>
  layui.use(['form', 'layer'], function () {

    var $ = layui.jquery,
            form = layui.form,
            layer = layui.layer;

    function loadWarehouseList() {
      $.ajax({
        url: '/storageLocation/list',
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({ onlyWarehouse: true }),
        success: function (res) {
          if (res.code === 0 && res.data && res.data.length > 0) {
            var select1 = $('#warehouseSelect');
            var select2 = $('#addWarehouseSelect');
            var select3 = $('#editWarehouseSelect');
            select1.empty().append('<option value="">全部</option>');
            select2.empty();
            select3.empty();
            res.data.forEach(function (item) {
              select1.append(`<option value="${item.warehouseId}">${item.warehouseName}</option>`);
              select2.append(`<option value="${item.warehouseId}">${item.warehouseName}</option>`);
              select3.append(`<option value="${item.warehouseId}">${item.warehouseName}</option>`);
            });
            form.render('select');
          }
        },
        error: function () {
          layer.msg('无法加载仓库列表');
        }
      });
    }

    // 渲染卡片
    function renderCards(data) {
      var html = '';
      data.forEach(function (item) {
        var percent = item.stockPercent ? parseFloat(item.stockPercent.replace('%', '')) : 0;
        var bgColorClass = 'normal';
        if (percent < 30) bgColorClass = 'low';
        else if (percent >= 100) bgColorClass = 'danger';
        else if (percent <100 && percent >= 70) bgColorClass = 'warning';

        html += `<div class="location-card ${bgColorClass}">
                  <div class="card-title">${item.locationName} (${item.locationCode})</div>
                  <div class="card-status">${item.stockPercent || '0%'}</div>
                  <div class="card-info">当前库存：${item.stock || 0}</div>
                  <div class="card-actions">
                                         <!-- 新增：查看存储物料 -->
                      <button class="layui-btn layui-btn-xs layui-btn-lime view-material-btn" data-id="${item.id}">查看物料</button>
                      <button class="layui-btn layui-btn-xs layui-btn-warm edit-btn" data-id="${item.id}">编辑</button>
                      <button class="layui-btn layui-btn-xs layui-btn-danger delete-btn" data-id="${item.id}" data-stock="${item.stock || 0}">删除</button>
                  </div>
               </div>`;
      });

      $('#locationCardList').html(html);
    }

    function fetchData() {
      var params = {
        warehouseId: $('[name=warehouseId]').val(),
        locationCode: $('[name=locationCode]').val(),
        locationName: $('[name=locationName]').val(),
        storageLocationStatus: $('[name=status]').val()
      };

      $.ajax({
        url: '/storageLocation/list',
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(params),
        beforeSend: function () { layer.load(2); },
        success: function (res) {
          layer.closeAll('loading');
          if (res.code === 0 && res.data) {
            renderCards(res.data);
          } else {
            layer.msg('数据加载失败');
          }
        },
        error: function () {
          layer.closeAll('loading');
          layer.msg('网络错误');
        }
      });
    }

    // 查看物料
    function showMaterialDialog(materialList) {
      let html = `<table class="layui-table">
            <thead>
                <tr>
                    <th>物料名称</th>
                    <th>批次号</th>
                    <th>过期时间</th>
                </tr>
            </thead>
            <tbody>
    `;

      materialList.forEach(function (item) {
        html += `<tr>
                <td>${item.materialName || '-'}</td>
                <td>${item.batchNumber || '-'}</td>
                <td>${item.expireDate || '-'}</td>
            </tr>`;
      });

      html += '</tbody></table>';

      layer.open({
        title: '库位物料信息',
        type: 1,
        shade: 0.2,
        maxmin: true,
        shadeClose: true,
        area: ['600px', '400px'],
        content: html
      });
    }

    $(function () {
      loadWarehouseList();
      fetchData();
    });

    // 搜索按钮
    form.on('submit(search-btn)', function (data) {
      fetchData();
      return false;
    });

    // 重置按钮
    $('#reset-btn').on('click', function () {
      $('#searchForm')[0].reset();
      form.render();
      fetchData();
    });

    // 打开添加弹窗
    $('#add-btn').on('click', function () {
      $('#addLocationForm')[0].reset();
      form.val('addLocationForm', { storageLocationStatus: 'low' });
      layer.open({
        title: '添加库位',
        type: 1,
        shade: 0.2,
        maxmin: true,
        shadeClose: true,
        area: ['400px', '450px'],
        content: $('#addLocationFormDialog')
      });
    });

    // 打开编辑弹窗
    $(document).on('click', '.edit-btn', function () {
      var id = $(this).data('id');

      $.ajax({
        url:  `/storageLocation/detail/${id}`,
        method: 'GET',
        contentType: 'application/json',

        success: function(res) {
          if (res.code === 0 && res.data && res.data) {
            var item = res.data;

            form.val('editLocationForm', {
              storageLocationCode: item.storageLocationCode,
              storageLocationName: item.storageLocationName,
              storageLocationType: item.storageLocationType,
              warehouseId: item.warehouseId,
              storageLocationTotalCapacity: item.storageLocationTotalCapacity,
              storageLocationUsedCapacity: item.storageLocationUsedCapacity,
              storageLocationStatus: item.storageLocationStatus === 1 ? 'low' :
                      item.storageLocationStatus === 2 ? 'normal' :
                              item.storageLocationStatus === 3 ? 'warning' : 'danger',
              storageLocationRemark: item.storageLocationRemark
            });

            $('#editLocationForm').data('edit-id', id);

            layer.open({
              title: '编辑库位',
              type: 1,
              shade: 0.2,
              maxmin: true,
              shadeClose: true,
              area: ['400px', '450px'],
              content: $('#editLocationFormDialog')
            });
          } else {
            layer.msg('数据加载失败');
          }
        },
        error: function () {
          layer.msg('请求失败，请检查网络或接口');
        }
      });
    });

    // 删除库位
    $(document).on('click', '.delete-btn', function () {
      var id = $(this).data('id');
      var stock = parseFloat($(this).data('stock'));

      if (stock > 0.0) {
        layer.msg("删除失败，请先清理库存");
        return;
      }

      layer.confirm("确定要删除该库位吗？", { icon: 3, title: '提示' }, function (index) {
        $.ajax({
          url: `/storageLocation/delete?id=${id}`,
          method: 'GET',
          success: function (res) {
            if (res.code === 0) {
              layer.msg("删除成功");
              fetchData(); // 刷新列表
            } else {
              layer.msg("删除失败：" + res.msg);
            }
          },
          error: function () {
            layer.msg("网络错误");
          }
        });
        layer.close(index);
      });
    });

    // 添加提交
    form.on('submit(saveAddLocationBtn)', function (data) {
      var formData = data.field;
      formData.storageLocationStatus = formData.storageLocationStatus === 'low' ? 1 :
              formData.storageLocationStatus === 'normal' ? 2 :
                      formData.storageLocationStatus === 'warning' ? 3 : 4;

      $.ajax({
        url: '/storageLocation/add',
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(formData),
        success: function () {
          layer.msg('保存成功');
          layer.closeAll();
          fetchData();
        },
        error: function () {
          layer.msg('保存失败');

        }

      });

      return false;
    });

    // 编辑提交
    form.on('submit(saveEditLocationBtn)', function (data) {
      var formData = data.field;
      var id = $('#editLocationForm').data('edit-id');

      // 注入 storageLocationId
      formData.storageLocationId = id;

      // 转换状态字段
      formData.storageLocationStatus = formData.storageLocationStatus === 'low' ? 1 :
              formData.storageLocationStatus === 'normal' ? 2 :
                      formData.storageLocationStatus === 'warning' ? 3 : 4;

      // 打印调试信息
      console.log("提交数据：", formData);

      // 使用 $.ajax 明确指定 content-type 为 application/json
      $.ajax({
        url: `/storageLocation/update`,
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(formData),
        success: function (res) {
          if (res.code === 0) {
            layer.msg("修改成功");
            fetchData(); // 刷新列表
          } else {
            layer.msg("修改失败：" + res.msg || "未知错误");
          }
          //layer.closeAll();
          $('#editLocationForm').removeData('edit-id');
        },
        error: function () {
          layer.msg("保存失败");
        }
      });

      return false;
    });

    // 查看物料按钮点击事件
    $(document).on('click', '.view-material-btn', function () {
      var id = $(this).data('id');

      // 发起请求获取库位下的物料信息
      $.ajax({
        url: '/storageLocation/materials/'+id,
        method: 'GET',
        //data: { id: id },
        beforeSend: function () {
          layer.load(2);
        },
        success: function (res) {
          layer.closeAll('loading');

          if (res.code === 0 && res.data && res.data.length > 0) {
            showMaterialDialog(res.data);
          } else {
            layer.msg("该库位暂无物料");
          }
        },
        error: function () {
          console.error('请求失败:', xhr.status, xhr.responseText); // 打印详细错误信息
          layer.closeAll('loading');
          layer.msg("网络错误，请重试");
        }
      });
    });


  });
</script>
</body>
</html>
